import re
from rest_framework import serializers
from users.models import User


class UserSerializer(serializers.ModelSerializer):
    """
        用户表序列化器
    """

    class Meta:
        # 指定生成序列化字段的模型类
        model = User
        # 指定字段
        fields = ('id', 'username', 'mobile', 'email', 'password')
        extra_kwargs = {
            "password": {
                'write_only': True,
                'max_length': 20,
                'min_length': 8
            },
            'username': {
                'max_length': 20,
                'min_length': 5
            }
        }

    # 手机号格式验证
    def validate_mobile(self, attrs):
        if not re.match(r'1[3-9]\d{9}', attrs):
            raise serializers.ValidationError('手机格式不正确')

        # 唯一值判断
        try:
            user = User.objects.get(mobile=attrs)
        except:
            user = None
        if user:
            raise serializers.ValidationError('手机号已注册')

        return attrs

    def create(self, validated_data):
        # 重写create方法进行密码加密
        # 第一种 先调用父类方法获取保存后的用户对象
        # user = super().create(validated_data)
        # # 用户对象中的set_password方进行密码加密
        # user.set_password(validated_data['password'])
        # user.save()

        # 第二种  直接进行密码加密保存  {name:python}  name=python
        user = User.objects.create_user(**validated_data)

        return user
